package com.rampage.multitimers.view;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rampage.multitimers.Main;
import com.rampage.multitimers.R;
import com.rampage.multitimers.bo.TimerConfig;
import com.rampage.multitimers.handler.TimerHandler;

public class TimerView extends LinearLayout {
	
	private LayoutInflater inflater = null;
	private ClockView clock;
	private int time;
	private int restingTime;
	private int alertTime;
	private TimerHandler handler;
	private boolean stopped = true;
	private TimerConfig config;
	private int soundId;
	//private boolean warningDone = false;

	public TimerConfig getConfig() {
		return config;
	}

	public TimerView(Context context) {
		super(context);
		init();
	}

	public TimerView(Context context, TimerConfig config) {
		super(context);
		this.config = config;
		soundId = Main.soundPool.load(config.filename, 1);
		init();
	}

	public TimerView(Context context, AttributeSet attributeSet) {
		super(context, attributeSet);
		init();
	}
	
	public void dec() {
		this.restingTime--;
		if (restingTime == -1) {
			restingTime = time-1;
			//warningDone = false;
		}
		if (restingTime == config.warningAt) {
    		if (config.voiceWarning) {
            	//Main.mTts.speak(config.name, TextToSpeech.QUEUE_ADD, null);
    			Main.soundPool.play(soundId, Main.volume, Main.volume, 1, 0, 1f);
    		} else {
   	        	Main.soundPool.play(Main.soundID, Main.volume, Main.volume, 1, 0, 1f);
    		}
		}

		clock.update(restingTime, alertTime, restingTime*1f/time);
	}
	
	public void toggle() {
		if (stopped) {
			start();
		} else {
			pause();
		}
	}
	public void start() {
		handler.startTimers();
		stopped = false;
		clock.setActive(true);
	}
	public void pause() {
		handler.stopTimers();
		restingTime = time;
		clock.update(restingTime, alertTime, restingTime*1f/time);
		stopped = true;
		clock.setActive(false);
		//warningDone = false;
	}
	private void init() {
		time = this.config.seconds;
		restingTime = time;
		//warningDone = false;
		alertTime = this.config.warningAt; 
		inflater = LayoutInflater.from(getContext());
		inflater.inflate(R.layout.timer, this);
		((TextView)findViewById(R.id.label)).setText(this.config.name);
		clock = (ClockView)findViewById(R.id.clock);
		clock.update(restingTime, alertTime, restingTime*1f/time);
		handler = new TimerHandler(this);
	}
}
